<?php
include "otamu_config.php";

$layout = "group_layout";
define("_VIEWPATH_","views/group/");

if (!isset($_GET['act'])) $_GET['act'] = ''; 

class ItemGroup extends ADOdb_Active_Record
{
	var $_table = 'item_groups';
}


switch ($_GET['act']) {
	case "new" :
		break;

	case "create" :
		if ($name=='') exitError("Sila Masukkan Nama Jabatan");
		//check if already exist group
		$sql = "SELECT name FROM item_groups WHERE name ilike '$_REQUEST[name]'";
		$n = pg_num_rows(pg_query($sql));
		
		if ($n>0) exitError("Item Group already exists.");

		$obj = new ItemGroup();

		$obj->name            = $_REQUEST['name'];
		$obj->dflt_graph_type = $_REQUEST['dflt_graph_type'];
		
		//print_r($obj);exit;

		if (!$obj->save()) { 
			$_SESSION['flash'] = $obj->ErrorMsg();
		}else {
			$_SESSION['flash'] = 'Item Group has been added';
		}
		header("Location: group.php?act=list");
		break;
		
	case "edit" :
		if (!isset($id) || $id=='') {
			exitError("Group not found.");
		}
		$sql = "SELECT * FROM item_groups WHERE id='$id'";
		$res = pg_query($sql);
		$dat = pg_fetch_object($res);
		$name = $dat->name;
		break;

	case "update" :
		if (!isset($id) || $id=='') {
			exitError("Item Group not found.");
		}
		$ig = new ItemGroup();

		$obj =  $ig->Find("id='$_REQUEST[id]'");
				
		if ($obj) { $obj = $obj[0];}
		//print_r($obj);exit;

		$obj->name            = $_REQUEST['name'];
		$obj->dflt_graph_type = $_REQUEST['dflt_graph_type'];

		if (!$obj->save()) { 
			$_SESSION['flash'] = $obj->ErrorMsg();
		}else {
			$_SESSION['flash'] = 'Item Group has been updated';
		}
		header("Location: group.php?act=list");
		
		break;

	case "destroy" :
		if (isset($id)) {
			$check = "SELECT DISTINCT(item_group_id) FROM items WHERE item_group_id='$id'";
			$n = pg_num_rows(pg_query($check));
			if ($n>0) {
				exitError("This group is still in use and cannot be deleted.");
			}
			$sql = "DELETE FROM item_groups WHERE id='$id'";
			$res = pg_query($sql);
			$_SESSION['flash'] = 'Item Group has been deleted';
			header("Location: group.php?act=list");
		}
		else {
			echo "group not found $btn";exit;
		}
		break;
	
	default :
		$act = "list";
		$sql = "SELECT g.*,gt.name as graph_type_name FROM item_groups g 
		        LEFT JOIN graph_types gt ON gt.id=g.dflt_graph_type
				ORDER BY name
		        ";
		$res = pg_query($sql);
		
}

include _VIEWPATH_."$layout.php";

?>
